package com.sunkai.math;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class FormatStringImpl implements FormatString {

	/**
	 * 
	 * @date 2018年2月6日 下午6:48:28
	 * @param str	str="132133大的366_3232  324 \r\n324324sd"
	 * @return		res="132133,366,3232,324,324324"
	 */
	@Override
	public String format(String str) {
		if (str == null || str.trim().length() == 0) {
			return str;
		}
		char[] array = str.toCharArray();
		char[] newChar = new char[array.length];
		int count = 0;
		boolean flag = false;
		for (int i=0;i<array.length;i++) {
			char c = array[i];
			if (c >='0' && c<='9') {
				newChar[count] = c; 
				count++;
				flag = false;
			} else {
				if (!flag && count != 0) {
					//非数字转成,
					newChar[count] = ',';
					count++;
					flag = true;
				}
			}
		}
		if(count>0&&newChar[count-1]==','){
			count--;
		}
		
		return new String(newChar,0,count);
	}

	
	public String readFile (InputStream in) throws IOException {
		byte[] b = new byte[in.available()];
		in.read(b);
		in.close();
		return new String(b);
	}
	
	public void writeFile() throws IOException {
		FileOutputStream fos = new FileOutputStream("E:\\tttt2.txt");
		StringBuilder sb = new StringBuilder("a");
		int count = 100;
		while (true) {
			sb.append(System.currentTimeMillis()).append("qqq");
			if (count -- == 0) {
				break;
			}
		}
		fos.write(sb.toString().getBytes());
		fos.flush();
		fos.close();
	}
	public static void main(String[] args) throws IOException {
		FormatStringImpl f = new FormatStringImpl();
		
//		InputStream is = FormatStringImpl.class.getClassLoader().getResourceAsStream("./test.txt");
		InputStream is = new FileInputStream(new File("E:\\tttt2.txt"));
		
		
		String src = f.readFile(is);
		long start = System.currentTimeMillis();
		String result = f.format(src);
		long end = System.currentTimeMillis();
		System.out.println("time : " + (end-start));
		
	}
}
